package archer.framework.utils;

import archer.framework.core.exception.BaseException;
import archer.framework.protocol.ArcherProtocolModule;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.util.Map;

/**
 * 签名工具类
 *
 * @author christ
 * @date 2015/9/29
 */
public class SignatureUtils {

    /**
     * 生成签名
     *
     * @param content
     * @param secretKey
     * @return
     */
    public static String genSignature(byte[] content, byte[] secretKey) {

        return ArcherProtocolModule.signatureGenerator.generate(content, secretKey);
    }

    /**
     * 根据请求参数生成签名
     *
     * @param content
     * @param secretKey
     * @return
     */
    public static String genSignature(Map<String, ? extends Object[]> content, byte[] secretKey, String exclude) {

        byte[] c = StringUtils.getBytesUtf8(RequestParamUtils.getQueryString(content, exclude));

        return genSignature(c, secretKey);
    }

    /**
     * 根据请求参数生成签名
     *
     * @param content
     * @param secretKey 16进制表示的secretKey字符串
     * @param exclude
     * @return
     */
    public static String genSignature(Map<String, ? extends Object[]> content, String secretKey, String exclude) {

        if (ValidateUtils.isEmpty(secretKey)) {
            throw new IllegalArgumentException("secretKey不能为空");
        }

        try {
            return genSignature(content, Hex.decodeHex(secretKey.toCharArray()), exclude);

        } catch (DecoderException e) {

            throw new BaseException(e);
        }
    }
}
